package com.example.day02.Custom;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

@SuppressLint("AppCompatCustomView")
public class CircleImageView extends ImageView {
    //声明圆形的半径
    int mRadius;
    Paint mPaint;
    float scale;//缩放比例
    public CircleImageView(Context context) {
        super(context);
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = getMeasuredHeight();
        int width = getMeasuredWidth();
        //要形成圆形，先画正方形，圆形为正方形内切圆
        int size=Math.min(height,width);
        mRadius=size/2;
        setMeasuredDimension(size,size);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);
        mPaint=new Paint();
        //获取图片
        Drawable drawable = getDrawable();
        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();//将图片转换成位图对象
            //图片平铺的渲染
            BitmapShader bitmapShader=new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            //计算比例
            scale=(mRadius*2.0f)/Math.min(bitmap.getWidth(),bitmap.getHeight());

            Matrix matrix = new Matrix();
            matrix.setScale(scale,scale);
            bitmapShader.setLocalMatrix(matrix);
            mPaint.setShader(bitmapShader);
            //绘制圆形
            canvas.drawCircle(mRadius,mRadius,mRadius,mPaint);

        }else {
            super.onDraw(canvas);
        }
    }
}
